package com.example.mfbq;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.mfbq.activities.ShowActivity;
import com.example.mfbq.arithmetic.Process;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Button clearBtn;
    private Button inputBtn;
    private EditText comeTimeTv;
    private EditText serveTimeTv;
    private int count = 1;
    private List<Process> processes = new ArrayList<>();
    private ListView dataLv;
    private LinearLayout linearLayout;
    private BaseAdapter baseAdapter;
    private LinearLayout.LayoutParams dataParams;
    private Button fcfsBtn;
    private Button sjfBtn;
    private Button hrrnBtn;
    private Button rrBtn;
    private Button mfbqBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportActionBar().setTitle("进程调度算法模拟");

        dataParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dip2px(MainActivity.this, 150));
        dataParams.setMargins(0,10,0,0);
        dataParams.gravity = Gravity.CENTER_HORIZONTAL;
        baseAdapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return 0;
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                return null;
            }
        };

        linearLayout = this.findViewById(R.id.table_title);

        dataLv = new ListView(MainActivity.this);
        dataLv.setLayoutParams(dataParams);
        dataLv.setAdapter(baseAdapter);
        linearLayout.addView(dataLv);

        clearBtn = this.findViewById(R.id.clear_data);
        clearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count = 1;

                linearLayout.removeViewAt(1);
                dataLv = new ListView(MainActivity.this);
                dataLv.setLayoutParams(dataParams);
                dataLv.setAdapter(baseAdapter);
                linearLayout.addView(dataLv);

                processes = new ArrayList<>();
            }
        });

        comeTimeTv = this.findViewById(R.id.come_time_txt);
        serveTimeTv = this.findViewById(R.id.serve_time_txt);
        inputBtn = this.findViewById(R.id.input_data);
        inputBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String come = comeTimeTv.getText().toString().trim();
                String serve = serveTimeTv.getText().toString().trim();
                if(come != null && serve != null && come.length()>0 && serve.length()>0){
                    try{
                        int ctime = Integer.parseInt(come);
                        int stime = Integer.parseInt(serve);
                        Process process = new Process(count, ctime, stime);
                        count++;
                        processes.add(process);

                        comeTimeTv.setText("");
                        serveTimeTv.setText("");

                        View dataItem = getLayoutInflater().inflate(R.layout.data_info_item, null);
                        TextView processIdTv = dataItem.findViewById(R.id.process_id);
                        processIdTv.setText(process.getProcessId()+"");
                        TextView processCTime = dataItem.findViewById(R.id.process_come_time);
                        processCTime.setText(process.getComeTime()+"");
                        TextView processSTime = dataItem.findViewById(R.id.process_serve_time);
                        processSTime.setText(process.getServeTime()+"");
                        dataLv.addFooterView(dataItem);
                        dataLv.smoothScrollToPosition(dataLv.getCount() - 1);

                    }catch(Exception e){
                        Toast.makeText(MainActivity.this, "数据格式错误", Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(MainActivity.this, "信息不完整", Toast.LENGTH_LONG).show();
                }
            }
        });

        fcfsBtn = this.findViewById(R.id.fcfs);
        sjfBtn = this.findViewById(R.id.sjf);
        hrrnBtn = this.findViewById(R.id.hrrn);
        rrBtn = this.findViewById(R.id.rr);
        mfbqBtn = this.findViewById(R.id.mfbq);

        mfbqBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogMFBQ();
            }
        });

        fcfsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pro = JSON.toJSONString(processes);
                Intent intent = new Intent(MainActivity.this, ShowActivity.class);
                Bundle data = new Bundle();
                data.putString("pro", pro);
                data.putInt("queueNum", 1);
                data.putString("arithmetic", "fcfs");
                intent.putExtras(data);
                startActivity(intent);
            }
        });

        sjfBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogSJF();
            }
        });

        hrrnBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pro = JSON.toJSONString(processes);
                Intent intent = new Intent(MainActivity.this, ShowActivity.class);
                Bundle data = new Bundle();
                data.putString("pro", pro);
                data.putInt("queueNum", 1);
                data.putString("arithmetic", "hrrn");
                intent.putExtras(data);
                startActivity(intent);
            }
        });

        rrBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogRR();
            }
        });
    }

    private boolean mfbqFight = false;
    private NumberPicker np;
    private NumberPicker npTime;
    private TextView queueNumTv;
    private TextView queueTimeTv;
    private int queueNum = 3;
    private int queueTime = 2;
    private void dialogMFBQ(){

        View v = getLayoutInflater().inflate(R.layout.mfbq_dialog, null);

        np = v.findViewById(R.id.process_num);
        npTime = v.findViewById(R.id.queue_time_di);
        queueNumTv = v.findViewById(R.id.queue_num_tip);
        queueTimeTv = v.findViewById(R.id.queue_time_tip);
        RadioGroup whetherFight = v.findViewById(R.id.mfbq_rg);

        np.setMinValue(1);
        np.setMaxValue(7);
        np.setValue(queueNum);
        queueNumTv.setText("你选择的队列数为："+queueNum);
        np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                queueNum = newVal;
                queueNumTv.setText("你选择的队列数为："+newVal);
            }
        });

        npTime.setMinValue(1);
        npTime.setMaxValue(6);
        npTime.setValue(queueTime);
        queueTimeTv.setText("你选择每个队列执行时间片的底数为："+queueTime);
        npTime.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                queueTime = newVal;
                queueTimeTv.setText("你选择每个队列执行时间片的底数为："+newVal);
            }
        });

        whetherFight.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case (R.id.mfbq_unfight):
                        mfbqFight = false;
                        break;
                    case (R.id.mfbq_fight):
                        mfbqFight = true;
                        break;
                }
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("MFBQ数据补充")
                .setView(v)
                .setNegativeButton("取消", null)
                .setPositiveButton("开始演示", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String pro = JSON.toJSONString(processes);
                        Intent intent = new Intent(MainActivity.this, ShowActivity.class);
                        Bundle data = new Bundle();
                        data.putInt("queueNum", queueNum);
                        data.putInt("queueTime", queueTime);
                        data.putString("arithmetic", "mfbq");
                        data.putCharSequence("pro", pro);
                        data.putBoolean("fight", mfbqFight);
                        intent.putExtras(data);
                        startActivity(intent);
                    }
                })
                .create().show();
    }

    private NumberPicker rrnp;
    private TextView rrnpTv;
    private int time = 1;
    private void dialogRR(){
        View v = getLayoutInflater().inflate(R.layout.rr_dialog, null);
        rrnp = v.findViewById(R.id.queue_time_di);
        rrnpTv = v.findViewById(R.id.queue_time_tip);

        rrnp.setMinValue(1);
        rrnp.setMaxValue(5);
        rrnp.setValue(time);
        rrnpTv.setText("你选择时间片的长度为："+time);
        rrnp.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                time = newVal;
                rrnpTv.setText("你选择时间片的长度为："+newVal);
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("RR数据补充")
                .setView(v)
                .setNegativeButton("取消", null)
                .setPositiveButton("开始演示", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String pro = JSON.toJSONString(processes);
                        Intent intent = new Intent(MainActivity.this, ShowActivity.class);
                        Bundle data = new Bundle();
                        data.putInt("time", time);
                        data.putString("pro", pro);
                        data.putInt("queueNum", 1);
                        data.putString("arithmetic", "rr");
                        intent.putExtras(data);
                        startActivity(intent);
                    }
                })
                .create().show();

    }

    private boolean sjfFight = false;
    private RadioGroup sjfRadio;
    private void dialogSJF(){
        View v = getLayoutInflater().inflate(R.layout.sjf_dialog, null);

        sjfRadio = v.findViewById(R.id.sjf_fight);
        sjfRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case (R.id.fight_yes):
                        sjfFight = true;
                        break;
                    case (R.id.fight_no):
                        sjfFight = false;
                        break;
                }
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("SJF数据补充")
                .setView(v)
                .setNegativeButton("取消", null)
                .setPositiveButton("开始演示", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String pro = JSON.toJSONString(processes);
                        Intent intent = new Intent(MainActivity.this, ShowActivity.class);
                        Bundle data = new Bundle();
                        data.putString("pro", pro);
                        data.putInt("queueNum", 1);
                        data.putString("arithmetic", "sjf");
                        data.putBoolean("sjfFight", sjfFight);
                        intent.putExtras(data);
                        startActivity(intent);
                    }
                })
                .create().show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        sjfFight = false;
        mfbqFight = false;
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
